package com.wxg.zxing.qrcode;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class CreateQRCode {

	public static void main(String[] args) {
		
		int width = 300;
		int height = 300;
		
		int logoWidth = width*2/10;
		int logoHeight = height*2/10;
		
		String content = "www.baidu.com";
		
		Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		hints.put(EncodeHintType.MARGIN, 1);
		
		try {
			BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
			String tmpdir = System.getProperty("java.io.tmpdir");
			File file = new File( tmpdir + "QrCode_" + System.nanoTime() + ".png");
			// Path path = file.toPath();
			// MatrixToImageWriter.writeToPath(bitMatrix, "png", path);
			BufferedImage QRCodeBufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
			
			BufferedImage combined = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
			Graphics2D g2 = (Graphics2D)combined.getGraphics();
			g2.drawImage(QRCodeBufferedImage, 0, 0, null);
			
			File logoFile = new File(CreateQRCode.class.getClassLoader().getResource("images/logo.jpg").getPath());
			BufferedImage logo = ImageIO.read(logoFile);
			
			g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f));
			
			int x = (width-logoWidth)/2;
			int y = (height-logoHeight)/2;
			
			g2.drawImage(logo, x, y, logoWidth, logoHeight, Color.WHITE, null);
			
			ImageIO.write(combined, "png", file);
			
			
			System.out.println( file.getAbsolutePath() );
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	
}
